# -*- coding: utf-8 -*-
import io
import sys

reload(sys)
sys.setdefaultencoding("utf-8")


class ConfigParser(object):
    def __init__(self, filename):
        self.filename = filename
        self.config = {}

    def parse(self):
        """ 解析配置文件并存储在字典中 """
        current_section = None

        with io.open(self.filename, 'r', encoding='utf-8') as f:
            for line in f:
                # 去除前后空格，并跳过空行和注释
                line = line.strip()
                if not line or line.startswith('#'):
                    continue

                # 如果是 [section] 行，则定义新的节
                if line.startswith('[') and line.endswith(']'):
                    current_section = line[1:-1].strip()
                    self.config[current_section] = {}
                # 解析 key = value 行
                elif '=' in line and current_section is not None:
                    key, value = line.split('=', 1)
                    self.config[current_section][key.strip()] = value.strip()
                else:
                    raise ValueError("Invalid configuration line: {}".format(line))

    def get(self, section, key):
        """ 获取指定 section 中的 key 对应的值 """
        try:
            return self.config[section][key]
        except KeyError:
            raise KeyError("Key '{}' not found in section '{}'".format(key, section))

    def get_section(self, section):
        """ 获取整个 section 作为字典 """
        try:
            return self.config[section]
        except KeyError:
            raise KeyError("Section '{}' not found".format(section))


# 测试代码
if __name__ == "__main__":
    config = ConfigParser('../../../conf/config.ini')
    config.parse()

    # 获取指定的配置项
    print("Database Host:", config.get('logger', 'max_bytes'))
    print("Database Host:", config.get('logger', 'test'))

    # 获取整个 section
    print("Database Config:", config.get_section('logger'))
